package com.isp.common.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.net.HttpURLConnection;
import java.util.Base64;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/11/18 14:16
 */
public class FileUtils {

    /**
     * 获取文件大小
     *
     * @return 文件大小（KB）
     */
    public static Long getFileSize(String fileUrl) {
        try (HttpResponse response = HttpUtil.createGet(fileUrl).timeout(60000).execute()) {
            int status = response.getStatus();
            if (status == HttpURLConnection.HTTP_OK) {
                // 获取 Content-Length 头部信息
                String contentLength = response.header("Content-Length");
                if (StringUtils.isNotBlank(contentLength)) {
                    long fileSize = Long.parseLong(contentLength);
                    return fileSize / 1024;
                } else {
                    return 0L;
                }
            } else {
                throw new RuntimeException("获取文件大小异常");
            }
        }
    }

    /**
     * 获取图片文件base64
     *
     * @param imageUrl 图片地址
     * @return base64
     */
    public static String getImageBase64(String imageUrl) {
        try (HttpResponse response = HttpUtil.createGet(imageUrl).timeout(60000).execute()) {
            int status = response.getStatus();
            if (status == HttpURLConnection.HTTP_OK) {
                BASE64Encoder encoder = new BASE64Encoder();
                return Base64.getEncoder().encodeToString(response.bodyBytes());
            } else {
                throw new RuntimeException("获取文件异常");
            }
        }
    }

    public static void main(String[] args) {
        String fileSize = getImageBase64("https://dev-minio.gxar.com:7892/develop/product/quick-ar/%E7%BE%8E%E6%B1%81%E6%BA%90%E5%9F%8E%E5%A0%A1%E8%AF%86%E5%88%AB%E5%9B%BE-1698141126937-1706063132009.jpg");
        System.out.println(fileSize);
    }

}
